#include "medicinetake.h"
#include "ui_medicinetake.h"
#include <QMessageBox>
#include "usermanager.h"

MedicineTakeWindow::MedicineTakeWindow(QWidget *parent)
    : QWidget(parent)
    , medicinetakewindowUi(new Ui::MedicineTakeWindow)
    , networkManager(new NetworkManager(this))
{
    medicinetakewindowUi->setupUi(this);
    connect(networkManager, &NetworkManager::takeMedicineResponseReceived, this, &MedicineTakeWindow::handleTakeMedicineResponse);
}

MedicineTakeWindow::~MedicineTakeWindow()
{
    delete medicinetakewindowUi;
}

void MedicineTakeWindow::on_takeButton_clicked()
{
    QString medicineName = medicinetakewindowUi->nameLineEdit->text();
    int quantity = medicinetakewindowUi->quantityLineEdit->text().toInt();

    if (medicineName.isEmpty() || quantity <= 0) {
        QMessageBox::warning(this, "输入错误", "请填写有效的药品名称和数量。");
        return;
    }

    QJsonObject json;
    json["username"] = UserManager::instance().getUsername();
    json["medicine_name"] = medicineName;
    json["quantity"] = quantity;

    networkManager->takeMedicine(json);
}

void MedicineTakeWindow::on_cancelButton_clicked()
{
    this->close();
}

void MedicineTakeWindow::handleTakeMedicineResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QMessageBox::information(this, "成功", "药品提取成功！");
        medicinetakewindowUi->nameLineEdit->clear();  // Clear input fields after successful extraction
        medicinetakewindowUi->quantityLineEdit->clear();
    } else {
        QMessageBox::warning(this, "错误", "药品提取失败：" + desc);
    }
}
